package com.ultrapower.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ultrapower.commons.base.BaseController;
import com.ultrapower.commons.result.PageInfo;
import com.ultrapower.commons.scan.Traced;
import com.ultrapower.commons.shiro.ShiroUser;
import com.ultrapower.commons.utils.StringUtils;
import com.ultrapower.model.Enterprise;
import com.ultrapower.model.EnterpriseOnline;
import com.ultrapower.model.Orderlist;
import com.ultrapower.model.Organization;
import com.ultrapower.model.Task;
import com.ultrapower.model.vo.UserVo;
import com.ultrapower.service.IEnterpriseOnlineService;
import com.ultrapower.service.IMapService;
import com.ultrapower.service.IOrderService;
import com.ultrapower.service.IOrganizationService;
import com.ultrapower.service.ITaskService;
import com.ultrapower.service.IUserService;
import com.ultrapower.task.UploadOrder;

/**
 * @description：工单
 * @author：polly
 * @date：2018-8-2 15:46:54
 */
@Controller
@RequestMapping("/order")
public class OrderController extends BaseController{

	@Autowired
    private IOrderService orderService;
	@Autowired 
	private ITaskService taskService;
	@Autowired
    private IEnterpriseOnlineService enterpriseOnlineService;
	@Autowired
    private IUserService userService;
	@Autowired
    private IOrganizationService orgService;
	@Autowired
    private IMapService mapService;
	
	/**
     * 工单管理主页
     *
     * @return
     */
    @GetMapping(value = "/manager")
    public String manager() {
        return "admin/order/order";
    }
    
    /**
     * 添加成员页
     *
     * @return
     */
    @GetMapping("/addOrder")
    public String addMember() {
        return "admin/order/addOrder";
    }
    
    /**
     * 创建工单
     *
     * @return
     */
    @GetMapping("/createOrder")
    public String createOrder() {
        return "admin/order/addPage";
    }
    
    /**
     * 成员列表
     *
     * @return
     */
    @GetMapping("/member")
    public String member() {
        return "admin/order/member";
    }
    
    /**
     * 订单添加——任务列表
     *
     * @return
     */
    @GetMapping("/taskList")
    public String taskList() {
        return "admin/order/taskList";
    }
    
    /**
     * 订单列表——任务列表
     *
     * @return
     */
    @GetMapping("/taskDetails")
    public String taskDtails() {
        return "admin/order/taskDetails";
    }
    
    /**
    * 订单列表——任务列表
    *
    * @return
    */
   @GetMapping("/allocatedlist")
   public String  allocatedlist() {
       return "admin/order/allocatedlist";
   }

    
    /**
     * 工单列表
     *
     * @param Orderlist
     * @param page
     * @param rows
     * @param sort
     * @param order
     * @return
     */
    @PostMapping("/dataGrid")
    @ResponseBody
    public Object dataGrid(Orderlist orderlist, Integer page, Integer limit, String sort, String order,String employeeId,String submitTime) {
    	//sort = "createTime";
    	sort = "id";
    	order = "asc";
    	UserVo user = null;
    	String name = orderlist.getName();
    	String city = orderlist.getCity();
    	String country = orderlist.getCountry();
        Map<String, Object> condition = new HashMap<String, Object>();
        PageInfo pageInfo = new PageInfo(page, limit, sort, order);
        ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
	        if(shiroUser.getRoles().contains("admin")||shiroUser.getRoles().contains("pcm")) {
	        	
	        	
	        }else if(shiroUser.getRoles().contains("cm")) {
	        	condition.put("creater", getUserId());
	        }
	        if(StringUtils.isNotBlank(employeeId)){
	        	user = userService.selectByEmployeeId(employeeId);
	        	if(user != null){
	        		//orderlist.setUserId(user.getId().intValue());
	        		condition.put("creater", user.getId().intValue());
	        	}
	        }
	        if (StringUtils.isNotBlank(name)) {
	            condition.put("name", name);
	        }
	        if (StringUtils.isNotBlank(city)) {
	            condition.put("city", city);
	        }
	        if (StringUtils.isNotBlank(country)) {
	            condition.put("country", country);
	        }
	        if (StringUtils.isNotBlank(submitTime)) {
	        	String[] stime = submitTime.split("\\ - ");
	        	String startTime = stime[0].trim();
	        	String endTime = stime[1].trim();
	            condition.put("startTime", startTime);
	            condition.put("endTime", endTime);
	        }
        pageInfo.setCondition(condition);
        orderService.selectDataGrid(pageInfo);
        return pageInfo;
    }
    
    /**
     * 工单列表
     *
     * @param Orderlist
     * @param page
     * @param rows
     * @param sort
     * @param order
     * @return
     */
    @PostMapping("/taskPage")
    @ResponseBody
    public Object taskPage(Enterprise enterprise, String companyName, String type, String orderId, String userId, Integer page, Integer limit, String sort, String order) {
    	sort = "id";
    	order = "asc";
        Map<String, Object> condition = new HashMap<String, Object>();
        PageInfo pageInfo = new PageInfo(page, limit, sort, order);
	        if (StringUtils.isNotBlank(userId)) {
	            condition.put("userId", userId);
	        }
	        if (StringUtils.isNotBlank(orderId)) {
	            condition.put("orderId", orderId);
	        }
	        if (StringUtils.isNotBlank(companyName)) {
	            condition.put("companyName", companyName);
	        }
	        type = taskService.selectTypeByOrderId(orderId,null);
	        condition.put("type", type);	        
//	        ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
//	        if(!shiroUser.getRoles().contains("admin")&&shiroUser.getRoles().contains("cm")) {
//	        	condition.put("creater", getUserId());		        	
//	        }
	        
        pageInfo.setCondition(condition);
        orderService.selectTaskPage(pageInfo);
        return pageInfo;
    }
    
    /**
     * 添加工单
     *
     * @param product
     * @return
     */
    @Traced(name="添加工单")
    @PostMapping("/add")
    @ResponseBody
    public Object add(@Valid Orderlist order,String Pproduct,String orgId,String Hotproduct,@RequestParam(value = "ids[]") Integer[] ids) {
    	ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
    	Long userId = user.getId();
    	//order.setUserId(userId.intValue());
		order.setCreateTime(new Date());
		order.setUpdateTime(new Date());
		order.setDeleteFlag(0);
		order.setCreater(userId);
		if(orgId!=null&&!"".equals(orgId)) {
			order.setUserId(userService.selectcmByorgId(orgId));
		}else {
			order.setUserId(getUserId());
		}
		orderService.insert(order);
    	for (int i = 0; i < ids.length; i++) {
    		Task task = new Task();
    		task.setOrderId(order.getId());
    		task.setEnterpriseId(ids[i]);
    		task.setCreater(userId);
    		task.setPrimaryProduct(Integer.parseInt(Pproduct));
    		task.setHotProduct(Integer.parseInt(Hotproduct));
    		task.setCreateTime(new Date());
    		task.setUpdateTime(new Date());
    		task.setType(0);
    		task.setDeleteFlag(0);
    		taskService.insert(task);
    	}
        return renderSuccess("添加成功");
    }
    
    /**
     * 添加
     * @param 
     * @return
     */
    @Traced(name="添加工单")
    @PostMapping("/addBatch")
    @ResponseBody
    public Object addBatch(int userId,String name,String describe,String taskIds) {
    	Organization org = orgService.selectOrgByUserId(getUserId());
    	Orderlist order = new Orderlist();
		order.setName(name);
		//order.setUserId(userId);
		order.setDescribe(describe);
		order.setCreateTime(new Date());
		order.setUpdateTime(new Date());
		order.setDeleteFlag(0);
		order.setCity(org.getCity());
		order.setCountry(org.getArea());
		order.setCreater(getUserId());
		boolean b=orderService.insert(order);
		if (b) {
    	for(String taskId:taskIds.split(";")) {
    		Task task = new Task();
    		task.setId(Integer.valueOf(taskId));
    		task.setOrderId(order.getId());
    		b = b&(taskService.updateById(task));
    	}
		}
         if (b) {
             return renderSuccess("添加成功！");
         } else {
             return renderError("添加失败！");
         }
    }
    
    @Traced(name="上传工单")
    @PostMapping("/upload")
    @ResponseBody
    public String uploadFile(HttpServletRequest request,MultipartFile file,String city,String area){
    	if("".equals(city) || "".equals(area)){
    		return "error";
    	}
    	//ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
    	JSONObject json = new JSONObject();
    	JSONObject jsonData = new JSONObject();
        try {
        	//文件上传路径
        	request.setCharacterEncoding("UTF-8");
            String path = request.getServletContext().getRealPath("/");
			String filename = file.getOriginalFilename();
			//写入本地磁盘
			InputStream is = file.getInputStream();
			byte[] bs = new byte[1024];
			int len;
			path = "/home/enterprise/file/orderFile/";
			File tmpfile = new File(path);
			if(!tmpfile.exists()){
				tmpfile.mkdir();
			}
			OutputStream os = new FileOutputStream(new File(path+filename));
			while ((len = is.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
			//int userId = user.getId().intValue();
			//这里做解析
			List<Map<String, String>> mapData = new UploadOrder().doUpload(path+filename);
			//这里批量添加
			//List<EnterpriseOnline> list = new ArrayList<EnterpriseOnline>();
			List<Integer> list = new ArrayList<Integer>();
//			List<Integer> listuserId = new ArrayList<Integer>();
			Map<String, String> rowData = null;
			boolean flag = true;
			//这里查询出来所有的历史公司名称，如果有重复的则不添加
			List<String> listName = mapService.selectAllName();
			for (int i = 0; i < mapData.size(); i++) {
					EnterpriseOnline eo = new EnterpriseOnline();
					rowData = mapData.get(i);
					if(!listName.contains(rowData.get("公司名称"))){
					//eo.setUserId(userId);
					eo.setName(rowData.get("公司名称"));
					eo.setAddress(rowData.get("公司地址"));
					eo.setCity(city);
					eo.setCountry(area);
					eo.setCreateTime(new Date());
//				UserVo userVo = userService.selectByEmployeeId(rowData.get("指派人员工号"));
//				if(userVo == null){
//					flag = false;
//					return "error";
//				}else{
//					//eo.setAppointingId(userVo.getId().intValue());
//				}
					enterpriseOnlineService.insert(eo);
					list.add(eo.getId());
//				listuserId.add(userVo.getId().intValue());
					//list.add(eo);
				}
			}
			//enterpriseOnlineService.insertBatch(list, 2000);
	    	json.put("code", 0);
	    	json.put("msg", "");
	    	jsonData.put("src", filename);
	    	jsonData.put("ids", list);
//	    	jsonData.put("userIds", listuserId);
	    	jsonData.put("flag", flag);
	    	json.put("data", jsonData);
			os.close();
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json.toString();
    }
}
